class Cart {
  constructor() {
    //购物车数据
    //如果之前买过，就把之前的数据取到，在此基础上继续增加
    if(localStorage.getItem("cartData")){
        this.cartData = JSON.parse(localStorage.getItem("cartData"));
    }else{
        this.cartData = {};
    }

  }
  saveData(pid,num,ter){
     //pid是商品id   ter布尔值 true表示最终值 false表示累加值
     //加入购物车时，先看有没有买过，如果没有，添加到购物车数据里，赋值为1，相当于买了1件
     if(this.cartData[pid]===undefined ||ter){
        this.cartData[pid] = num;
     }else{
        this.cartData[pid]+=num;
     }

     //存本地，便于其他页面使用该数据
     localStorage.setItem("cartData",JSON.stringify(this.cartData));
  }

  showList(id){
     //id放列表的容器的id
    
    let oUl = document.getElementById(id);
    let productDatas = JSON.parse(localStorage.getItem("good-data"));
    console.log(productDatas)
    let str = "";
    for(let pid in this.cartData){
      console.log(pid)
        let product = productDatas.find((item) =>item.pid==pid);
        console.log(product)
        str +=`
        <li class='li' data-id='${pid}'>
        <input type='checkbox' class='ck'>
        <img src="${product.pimg}">
        <span>${product.pname}</span>
        <span class='perPrice'>${product.pprice}</span>
        <button class='minus'>-</button>
        <input type="text" class='num' value='${this.cartData[pid]}'></input>
        <button class='plus'>+</button>
        <span class='perTotalPrice'>${product.pprice * this.cartData[pid]}</span>
        <button class='del'>删除</button>
        </li>
        `
    }
    oUl.innerHTML = str;
   

    let checkAll = document.getElementById("checkAll");
    this.lis = document.querySelectorAll('.li')
    this.cks = document.querySelectorAll(".ck");
    this.perPrice = document.querySelectorAll(".perPrice");
    this.minus = document.querySelectorAll(".minus");
    this.plus = document.querySelectorAll(".plus");
    this.nums = document.querySelectorAll(".num");
    this.perTotalPrice = document.querySelectorAll(".perTotalPrice");
    this.dels = document.querySelectorAll(".del");
    this.totalPrice = document.getElementById("totalPrice");

    //全选不全选
   if(checkAll){
      checkAll.onclick=()=>{
         this.cks.forEach((item)=>{
            item.checked = checkAll.checked;
         });
         this.getTotalPrice();
       }
   }

     //单击单个复选框，如果选中的数量和总数量保持一致，全选复选框选中
     this.cks.forEach((item)=>{
      item.onclick=()=>{
         let len1 = this.cks.length;
         let len2 = document.querySelectorAll('.ck:checked').length;
         if(len1==len2){
            checkAll.checked = true;
         }else{
            checkAll.checked = false;
         }
         this.getTotalPrice();
      }
     })


     for(let i =0;i<this.lis.length;i++){
      //减
      this.minus[i].onclick=()=>{
         this.nums[i].value--;
         if(this.nums[i].value<1){
            this.nums[i].value=1;
         }
        this.updateData(i);
       this.getTotalPrice();
      
      }

        //加
     this.plus[i].onclick=()=>{
      this.nums[i].value++;
      this.updateData(i);
      this.getTotalPrice();
     }
      //数量改变
      this.nums[i].onblur = () => {
         if (this.nums[i].value < 1) {
           this.nums[i].value = 1;
         }
         this.updateData(i);
         this.getTotalPrice();
       }

     //删
     this.dels[i].onclick=()=>{
      //移结构
      this.lis[i].remove();
      this.cks[i].checked = false;
      //清数据
      let pid = this.lis[i].getAttribute("data-id");
      delete this.cartData[pid];
      localStorage.setItem("cartData",JSON.stringify(this.cartData));
      // this.updateData(i);
      this.getTotalPrice();
     }

     }
  }
  updateData(i){
   //购物车数据变化，并且变化之后，要重新存到cookie里
   let pid = this.lis[i].getAttribute("data-id");
   this.saveData(pid,parseInt(this.nums[i].value),true);
   //单个总价变化
  this.perTotalPrice[i].innerHTML = this.nums[i].value*this.perPrice[i].innerText;

 } 

 getTotalPrice(){
   //总价的变化
   let tp=0;
   this.cks.forEach((item,idx)=>{
      if(item.checked){
         tp += parseInt(this.perTotalPrice[idx].innerText);
        }
   })
  
   this.totalPrice.innerHTML = `共计：￥${tp}`;
 }
}
